<template>
  <view class="list">
    <singleHeader class="boxHeight">
      <view class="headerNav">
        <view
          class="item"
          :class="[getMenuClass(item.sort_type)]"
          v-for="item of menus"
          :key="item.sort_type"
          @click="changeMenus(item.sort_type)"
        >
          {{ item.name }}
        </view>
      </view>
    </singleHeader>

    <pageHeader
      class="boxHeight"
      :categoryList="categoryList"
      :catId="cat_id"
      :scrollIntoView="scrollIntoView"
      :statusBarHeight="statusBarHeight"
      @change="handleClickTab"
    ></pageHeader>

    <scroll-view
      class="scrollViewX"
      scroll-x="true"
      :scroll-into-view="scrollIntoView"
      scroll-anchoring
      scroll-with-animation
      :style="{
        top: `${scrollTopY}px`
      }"
    >
      <swiper class="swiper" @change="changeSwiper" :current="current">
        <swiper-item
          class="swiperItem"
          v-for="(item, key) of listData"
          :key="key"
        >
          <scroll-view
            class="scrollViewY"
            scroll-y="true"
            :scroll-into-view="scrollIntoView"
            scroll-anchoring
            scroll-with-animation
            :refresher-enabled="refresherEnabled"
            :refresher-triggered="refresherTtriggered"
            @scrolltolower="scrolltolower"
            @refresherrefresh="refresherrefresh"
          >
            <u-waterfall :value="item.list" ref="waterfall" idKey="id">
              <template v-slot:left="{ leftList }">
                <list :list="leftList" @like="like" :isWaterfall="true"></list>
              </template>
              <template v-slot:right="{ rightList }">
                <list :list="rightList" @like="like" :isWaterfall="true"></list>
              </template>
            </u-waterfall>

            <view class="noMore">{{ $t("home.noMore") }}</view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </scroll-view>

    <view class="addForm" @click="add">
      <i class="iconfont icon-video"></i>
      <view class="text">{{ $t("videoGoods.list.add") }}</view>
    </view>
    <!-- 全局过渡组件 -->
    <transitionPage></transitionPage>
  </view>
</template>

<script>
import singleHeader from "@/components/diySystemPage/components/singleHeader/index.vue";
import { diySysPageMixin } from "@/components/diySystemPage/mixins/index";
import videoClassify from "@/api/videoClassify";
import pageHeader from "./components/page-header";
import list from "../components/list.vue";

export default {
  components: {
    singleHeader,
    pageHeader,
    list
  },

  mixins: [diySysPageMixin], //混入文件

  data() {
    return {
      menus: [
        { name: this.$t("videoGoods.list.follow"), sort_type: 1 },
        { name: this.$t("goods.recommend"), sort_type: 0 },
        { name: this.$t("list.latest"), sort_type: 2 }
      ],
      sort_type: 0,
      categoryList: [],
      cat_id: undefined,
      scrollIntoView: "",
      scrollTopY: 0,
      current: 0,
      listData: {},
      isOpenAdd: false,
      isAuthor: false,

      refresherEnabled: true,
      refresherTtriggered: false
    };
  },

  computed: {
    // isAuthor() {
    //   let userInfo = uni.getStorageSync("userInfo");
    //   if (!userInfo || userInfo.is_video_author !== 1) {
    //     return false;
    //   }

    //   return true;
    // },

    menuButtonStyle() {
      // #ifdef APP-PLUS || H5
      let obj = {
        top: this.statusBarHeight + "px",
        height: "88rpx",
        lineHeight: "88rpx"
      };
      // #endif
      // #ifndef APP-PLUS || H5
      let obj = {
        top: this.menuButtonInfo.top + "px",
        height: this.menuButtonInfo.height + "px"
      };
      // #endif

      return obj;
    },

    getMenuClass() {
      return (oldValue) => {
        return oldValue === this.sort_type ? "active" : "";
      };
    }
  },

  onShow() {
    videoClassify.videoAuditApplyConfig().then((res) => {
      if (res.code === 0) {
        this.isOpenAdd = res.data.is_author_audit;
        this.isAuthor = res.data.is_author;
        this.isApply = res.data.is_apply;
      }
    });
  },

  onLoad() {
    this.getCategoryList();
  },

  methods: {
    getCategoryList() {
      let categoryList = [],
        listData = {};

      videoClassify.categoryList().then((res) => {
        if (res.code === 0) {
          categoryList = res.data || [];

          if (categoryList.length) {
            this.cat_id = categoryList[0].id;

            categoryList.forEach((el, i) => {
              listData[i] = {
                id: el.id,
                page: 1,
                list: [],
                count: 0,
                isEnd: false
              };
            });
          }

          this.listData = listData;
          this.categoryList = categoryList;
          this.videoGoodsList();
        }

        this.$nextTick(() => {
          this.init();
        });
      });
    },

    clearData(fn) {
      let { categoryList, current, listData } = this,
        cat_id = categoryList[current].id,
        index = categoryList.findIndex((el) => el.id === cat_id);

      listData[index] = {
        page: 1,
        list: [],
        count: 0,
        isEnd: false
      };

      this.$refs.waterfall[current].clear();

      this.videoGoodsList(fn);
    },

    videoGoodsList(fn) {
      let { categoryList, current, sort_type, listData } = this,
        cat_id = categoryList[current].id,
        item = listData[current],
        { list: oldList, page } = item,
        limit = 20;

      if (item.isEnd) {
        return;
      }
      videoClassify
        .videoGoodsList({
          sort_type,
          limit,
          page,
          cat_id
        })
        .then((res) => {
          if (fn) {
            fn();
          }

          if (res.code === 0) {
            let { list, row_count } = res.data;
            item.count = parseInt(row_count);
            if (list.length) {
              oldList.push(...list);
              item.page = item.page + 1;
            }

            if (oldList.length >= item.count) {
              item.isEnd = true;
            }
          }
        })
        .catch(() => {
          if (fn) {
            fn();
          }
        });
    },

    like(item) {
      let { id, is_like } = item;
      // let { listData, cat_id } = this;
      // let newItem = listData[cat_id].list.find((el) => el.id === id);
      let { current } = this;

      let el = this.$refs.waterfall[current];

      if (is_like === 0) {
        videoClassify
          .videoGoodsVote(
            {
              vl_id: id,
              type: "1"
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              // this.$set(newItem, "is_like", 1);
              // this.$set(
              //   newItem,
              //   "like_count",
              //   parseInt(newItem.like_count) + 1
              // );
              el.modify(id, "is_like", 1);
              el.modify(id, "like_count", parseInt(item.like_count) + 1);
            }
          });
      } else {
        videoClassify
          .videoGoodsCancelVote(
            {
              vl_id: id,
              type: "1"
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              // this.$set(newItem, "is_like", 0);
              // this.$set(
              //   newItem,
              //   "like_count",
              //   parseInt(newItem.like_count) - 1
              // );
              el.modify(id, "is_like", 0);
              el.modify(id, "like_count", parseInt(item.like_count) - 1);
            }
          });
      }
    },

    init() {
      let info = uni.createSelectorQuery().selectAll(".boxHeight");
      info
        .boundingClientRect((data) => {
          data.forEach((el) => {
            this.scrollTopY += el.height;
          });
        })
        .exec();
    },

    changeMenus(newSortType) {
      let { sort_type, listData, current } = this;
      if (sort_type === newSortType) {
        return;
      }

      this.sort_type = newSortType;

      for (let i in listData) {
        listData[i] = {
          page: 1,
          list: [],
          count: 0,
          isEnd: false
        };
      }

      let elList = this.$refs["waterfall"];
      if (elList.length) {
        elList.forEach((el) => {
          el.clear();
        });
      }

      this.videoGoodsList();
    },

    changeCatId(id) {
      this.cat_id = id;
      this.scrollIntoView = `item${id}`;

      this.videoGoodsList();
    },

    handleClickTab(id) {
      this.current = this.categoryList.findIndex((el) => el.id === id);
    },

    changeSwiper(e) {
      let { current } = e.detail;
      this.current = current;
      this.changeCatId(this.categoryList[current].id);
    },

    // 滚动到底部
    scrolltolower() {
      this.videoGoodsList();
    },

    // 上传
    add() {
      let { categoryList, isOpenAdd, isAuthor, isApply } = this;

      if (isOpenAdd && !isAuthor) {
        if (isApply) {
          this.$utils.showModal(
            "提示",
            "已经提交审核请耐心等待！",
            false,
            () => {
              uni.navigateBack({
                delta: 1
              });
            }
          );
          return;
        }
        this.$utils.toUrl("/videoGoods/register/index");
        return;
      }

      uni.showActionSheet({
        //  this.$t("videoGoods.userInfo.video") // 视频
        itemList: [
          this.$t("videoGoods.list.photograph"),
          this.$t("videoGoods.userInfo.video")
        ],
        success: ({ tapIndex }) => {
          uni.navigateTo({
            url: `/videoGoods/add/index`,

            success(res) {
              res.eventChannel.emit("acceptDataFromOpenedPage", {
                type: tapIndex === 0 ? "2" : "1",
                categoryList: categoryList.filter((el) => el.id)
              });
            }
          });
        }
      });
    },

    refresherrefresh() {
      if (this.refresherTtriggered) return;
      this.refresherTtriggered = true;

      this.clearData(() => {
        this.refresherTtriggered = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.headerNav {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: normal;
  color: #262626;
  font-size: 30rpx;

  .item {
    padding: 0 16rpx;
    -webkit-transition: 0.3s all;
    transition: 0.3s all;
  }

  .active {
    font-size: 40rpx;
    font-weight: bold;
  }
}

.scrollViewX {
  position: absolute;
  left: 0;
  bottom: env(safe-area-inset-bottom);
}

.swiper,
.swiperItem,
.scrollViewY {
  height: 100%;
}

.scrollViewY {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  // padding-bottom: 40rpx;
  background: #f2f2f2;
}

.xItem {
  height: 300rpx;
}

.noMore {
  padding: 40rpx 0;
  font-size: 22rpx;
  text-align: center;
  color: #c1c1c1;
}

.addForm {
  position: fixed;
  right: 0;
  bottom: 148rpx;
  display: flex;
  align-items: center;
  padding: 10rpx 14rpx 10rpx 20rpx;
  background: #f0250e;
  border-radius: 32px 0 0 32px;
  color: #fff;

  .iconfont {
    font-size: 40rpx;
  }

  .text {
    margin-left: 8rpx;
    font-size: 28rpx;
  }
}
</style>
